<script setup lang="ts">
import api from "@/api";
import {reactive, watch, computed} from "vue";
import { onShow } from '@dcloudio/uni-app';
import { getTodayPunch } from '@/api/punch';
import { useUserStore } from '@/store';

const userStore = useUserStore()

const props = defineProps<{
  classInfo: Awaited<ReturnType<typeof api.classes.getClassInfoByClassId>>["data"]
    & Awaited<ReturnType<typeof api.classes.getClassesByCurrentUser>>["data"][number];
}>()

// 活动数据接口，与学习打卡页面保持一致
interface ActivityItem {
  id: number
  userId: number
  username: string
  timeDesc: string
  checkinDesc: string
  readingTitle: string
  readingCount: string
  commentText?: string
  avatarText: string
  avatarBg: string
  books: Array<{
    id: number
    title: string
    cover: string
  }>
  fullTime: string
  dayCount: number
}

const data = reactive<{
  activityList: ActivityItem[];
  todayReadingBooks: number;
  todayChecked: boolean;
}>({
  activityList: [],
  todayReadingBooks: 0,
  todayChecked: false,
});

// 检查当前用户是否为学生（只有学生才能打卡）
const isStudent = computed(() => {
  return props.classInfo?.role === 'student'
})

// 按钮禁用状态
const isButtonDisabled = computed(() => {
  return data.todayReadingBooks === 0 || !isStudent.value
})

// 是否显示打卡按钮
const showPunchButton = computed(() => {
  return isStudent.value
})

// 获取按钮文本
const getButtonText = () => {
  if (!isStudent.value) {
    return '老师无需打卡'
  }
  if (data.todayReadingBooks === 0) {
    return '请先阅读绘本'
  }
  return data.todayChecked ? `今日已读${data.todayReadingBooks}本，重新打卡` : `今日读了${data.todayReadingBooks}本，打个卡`
}

// 格式化时间描述 - 与学习打卡页面保持一致
const formatTimeDesc = (timeStr: string): string => {
  const now = new Date()
  const time = new Date(timeStr)
  const diff = now.getTime() - time.getTime()
  const minutes = Math.floor(diff / (1000 * 60))

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`

  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小时前`

  const days = Math.floor(hours / 24)
  if (days < 7) return `${days}天前`

  // 超过7天时，显示 yyyy/mm/dd 格式
  const year = time.getFullYear()
  const month = (time.getMonth() + 1).toString().padStart(2, '0')
  const day = time.getDate().toString().padStart(2, '0')

  return `${year}/${month}/${day}`
}

// 将班级打卡数据转换为活动列表格式
const convertToActivityList = (punchRecords: any[]): ActivityItem[] => {
  return punchRecords.map(punch => {
    // 处理用户信息显示
    const userInfo = punch.userInfo
    const displayName = userInfo?.nickname || userInfo?.username || `用户${userInfo?.userId || 'unknown'}`
    const avatarText = displayName.charAt(0).toUpperCase()

    return {
      id: punch.id,
      userId: userInfo?.userId,
      username: displayName,
      timeDesc: formatTimeDesc(punch.createTime || punch.updateTime || new Date().toISOString()),
      checkinDesc: `打卡第${punch.dayCount}天，读了${punch.bookCount}本`,
      readingTitle: `今天读了${punch.bookCount}本书`,
      readingCount: `读了${punch.bookCount}本`,
      commentText: punch.commentText,
      avatarText: avatarText,
      avatarBg: '#6c5ce7',
      avatarLoadError: false, // 初始化头像加载错误状态
      userInfo: punch.userInfo, // 保留完整的用户信息
      books: punch.books?.map((book: any) => ({
        id: book.id,
        title: book.title && book.title.length > 8 ? book.title.substring(0, 8) + '...' : book.title || '未知绘本',
        cover: book.cover || ''
      })) || [],
      fullTime: punch.createTime || punch.updateTime || new Date().toISOString(),
      dayCount: punch.dayCount
    }
  })
}

// 检查今日打卡状态
const checkTodayPunchStatus = async () => {
  try {
    const todayPunchResponse = await getTodayPunch()

    if (todayPunchResponse.code === 0) {
      // 如果有数据说明今日已打卡，如果为null说明未打卡
      data.todayChecked = !!todayPunchResponse.data
    }
  } catch (error) {
    console.error('检查打卡状态失败:', error)
  }
}

watch(() => props.classInfo, async ({id}) => {
  try {
    // 并行获取打卡记录和今日阅读记录
    const [punchResp, todayReadingResp] = await Promise.all([
      api.classes.getPunchRecordsByClassId(id),
      api.readingRecords.getTodayReadingRecords()
    ])

    // 处理打卡记录
    if (punchResp.code === 0) {
      data.activityList = convertToActivityList(punchResp.data)
    } else {
      uni.showToast({
        title: punchResp.msg,
        duration: 2000,
        icon: "error",
      })
    }

    // 处理今日阅读记录
    if (todayReadingResp.code === 0) {
      data.todayReadingBooks = (<any>todayReadingResp.data).readBookCount
    }

    // 检查今日打卡状态
    await checkTodayPunchStatus()
  } catch (error) {
    console.error('获取班级数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      duration: 2000,
      icon: "error",
    })
  }
}, {immediate: true});

// 页面显示时重新检查打卡状态
onShow(() => {
  checkTodayPunchStatus()
});

// 头像加载错误处理
function handleAvatarError(activity: any) {
  console.log('头像加载失败，切换到文字头像:', activity.username)
  activity.avatarLoadError = true
}

async function onPunchBtnClick() {
  // 如果按钮被禁用，不执行任何操作
  if (data.todayReadingBooks <= 0) {
    return;
  }

  if (!data.todayChecked) {
    // 首次打卡，跳转到打卡页面
    uni.navigateTo({
      url: `/pages/checkin/index?bookCount=${data.todayReadingBooks}`
    })
  } else {
    // 已打卡，支持重新打卡
    try {
      const todayPunchResponse = await getTodayPunch()
      if (todayPunchResponse.code === 0 && todayPunchResponse.data) {
        const punchRecord = todayPunchResponse.data
        // 跳转到重新打卡页面，传递现有打卡记录信息
        uni.navigateTo({
          url: `/pages/checkin/index?bookCount=${data.todayReadingBooks}&isRepunch=true&punchId=${punchRecord.id}&existingContent=${encodeURIComponent(punchRecord.commentText || '')}`
        })
      } else {
        // 如果获取不到打卡记录，按首次打卡处理
        uni.navigateTo({
          url: `/pages/checkin/index?bookCount=${data.todayReadingBooks}`
        })
      }
    } catch (error) {
      console.error('获取今日打卡记录失败:', error)
      uni.showToast({
        title: '获取打卡信息失败',
        icon: 'none'
      })
    }
  }
}
</script>

<template>
  <view class="checkin-container">
    <!-- 打卡按钮 - 只有学生才显示 -->
    <view v-if="showPunchButton" class="checkin-button">
      <view
        class="checkin-btn"
        :class="{ checked: data.todayChecked, disabled: isButtonDisabled }"
        @click="onPunchBtnClick()"
      >
        <text class="checkin-text">{{ getButtonText() }}</text>
      </view>
    </view>

    <!-- 老师提示信息 -->
    <view v-else class="teacher-info">
      <text class="teacher-text">老师可以查看班级打卡动态，但无需打卡</text>
    </view>

    <!-- 打卡动态列表 - 与学习打卡页面保持一致 -->
    <view class="activity-list">
      <view v-if="data.activityList.length === 0" class="empty-state">
        <text class="empty-text">暂无班级打卡记录</text>
      </view>
      <view v-else v-for="activity in data.activityList" :key="activity.id" class="activity-item">
        <view class="user-header">
          <view class="user-avatar">
            <!-- 优先显示用户头像图片 -->
            <image
              v-if="activity.userInfo?.avatar && !activity.avatarLoadError"
              :src="activity.userInfo.avatar"
              class="avatar-image"
              mode="aspectFill"
              @error="handleAvatarError(activity)"
            />
            <!-- 头像加载失败或没有头像时显示文字头像 -->
            <text v-else class="avatar-text" :style="{ backgroundColor: activity.avatarBg }">{{ activity.avatarText }}</text>
          </view>
          <view class="user-info">
            <view class="user-name-row">
              <text class="username">{{ activity.username }}</text>
              <text class="time-desc">{{ activity.timeDesc }}</text>
            </view>
            <text class="checkin-desc">{{ activity.checkinDesc }}</text>
          </view>
        </view>

        <view class="reading-content">
          <text class="reading-title">{{ activity.readingTitle }}</text>
          <text class="reading-count">{{ activity.readingCount }}</text>

          <!-- 用户心得 -->
          <view class="comment-content" v-if="activity.commentText">
            <text class="comment-text">{{ activity.commentText }}</text>
          </view>

          <view class="book-list" v-if="activity.books && activity.books.length > 0">
            <view v-for="book in activity.books" :key="book.id" class="book-item">
              <image class="book-cover" :src="book.cover" mode="aspectFill" />
              <text class="book-title">{{ book.title }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
@import '@/styles/variables.scss';

// 导入公共样式混入
@mixin card-container {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: $border-radius-xl;
  box-shadow: $shadow-lg;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

@mixin click-scale {
  transition: $transition-all;

  &:active {
    transform: scale(0.98);
  }
}

@mixin text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.checkin-container {
  /* 打卡按钮 - 与学习打卡页面保持一致 */
  .checkin-button {
    padding: 0px $spacing-md $spacing-lg $spacing-lg;
    @include center-flex;

    .checkin-btn {
      width: 85%;
      height: $height-lg;
      background: $blue-gradient;
      color: $white;
      border: none;
      border-radius: $border-radius-3xl;
      box-shadow: $shadow-blue;
      font-family: $font-family;
      font-size: $font-size-md;
      font-weight: $font-weight-semibold;
      cursor: pointer;
      transition: $transition-all;
      @include center-flex;

      &.checked {
        background: $green-gradient;
        box-shadow: $shadow-green;

        &:hover {
          box-shadow: 0 6px 16px rgba(50, 205, 50, 0.4);
        }
      }

      &.disabled {
        background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
        box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
        cursor: not-allowed;

        &:hover {
          transform: none;
          box-shadow: 0 2px 8px rgba(153, 153, 153, 0.2);
        }

        &:active {
          transform: none;
        }

        .checkin-text {
          color: #666666;
          text-shadow: none;
        }
      }

      .checkin-text {
        color: $white;
        font-family: $font-family;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      }

      &:hover:not(.disabled) {
        transform: translateY(-2px);
      }

      &:active:not(.disabled) {
        transform: translateY(0) scale(0.98);
      }
    }
  }

  .activity-list {
    .empty-state {
      text-align: center;
      padding: $spacing-3xl;

      .empty-text {
        font-size: $font-size-lg;
        color: $medium-gray;
        font-family: $font-family;
      }
    }

    .activity-item {
      padding: $spacing-lg;
      border-bottom: 1px solid $border-color-light;
      border-radius: $border-radius-lg;
      margin-bottom: $spacing-md;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.95) 100%);
      backdrop-filter: blur(10px);
      box-shadow: 0 2px 12px rgba(66, 187, 255, 0.1);
      border: 1px solid rgba(66, 187, 255, 0.1);
      transition: $transition-all;
      position: relative;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(66, 187, 255, 0.15);
      }

      &:active {
        transform: translateY(0) scale(0.98);
      }

      .user-header {
        display: flex;
        align-items: flex-start;
        margin-bottom: $spacing-md;

        .user-avatar {
          width: $avatar-md;
          height: $avatar-md;
          margin-right: $spacing-md;
          border-radius: 50%;
          overflow: hidden;
          position: relative;

          .avatar-image {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }

          .avatar-text {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: $white;
            font-size: $font-size-lg;
            font-weight: $font-weight-bold;
            font-family: $font-family;
            box-shadow: $shadow-md;
          }
        }

        .user-info {
          flex: 1;

          .user-name-row {
            display: flex;
            align-items: center;
            margin-bottom: $spacing-xs;

            .username {
              font-size: $font-size-md;
              color: $dark-gray;
              font-weight: $font-weight-semibold;
              margin-right: $spacing-sm;
              font-family: $font-family;
              max-width: 120px;
              @include text-ellipsis;
            }

            .time-desc {
              font-size: $font-size-sm;
              color: $medium-gray;
              margin-right: auto;
              font-family: $font-family;
            }
          }

          .checkin-desc {
            font-size: $font-size-base;
            color: $medium-gray;
            font-family: $font-family;
          }
        }
      }

      .reading-content {
        .reading-title {
          display: block;
          font-size: $font-size-md;
          color: $dark-gray;
          font-weight: $font-weight-semibold;
          margin-bottom: $spacing-xs;
          font-family: $font-family;
        }

        .reading-count {
          font-size: $font-size-base;
          color: $medium-gray;
          margin-bottom: $spacing-md;
          font-family: $font-family;
        }

        /* 用户心得内容 */
        .comment-content {
          background: rgba(66, 187, 255, 0.05);
          padding: $spacing-md;
          border-radius: $border-radius-md;
          margin: $spacing-md 0;
          border-left: 3px solid $primary-blue;

          .comment-text {
            font-size: $font-size-base;
            color: $dark-gray;
            line-height: 1.6;
            font-family: $font-family;
            word-wrap: break-word;
          }
        }

        .book-list {
          display: flex;
          overflow-x: auto;
          gap: $spacing-md;
          padding: $spacing-sm 0;
          margin-top: $spacing-md;

          .book-item {
            flex-shrink: 0;
            width: 80px;
            text-align: center;

            .book-cover {
              width: 100%;
              height: 100px;
              object-fit: cover;
              border-radius: $border-radius-md;
              margin-bottom: $spacing-xs;
              box-shadow: $shadow-sm;
              background: $light-gray;
            }

            .book-title {
              font-size: $font-size-xs;
              color: $medium-gray;
              font-family: $font-family;
              @include text-ellipsis;
            }
          }
        }
      }
    }
  }

  /* 老师提示信息样式 */
  .teacher-info {
    padding: $spacing-lg;
    text-align: center;
    background: rgba(108, 117, 125, 0.1);
    border-radius: $border-radius-lg;
    margin: $spacing-lg;

    .teacher-text {
      font-size: $font-size-base;
      color: $medium-gray;
      font-family: $font-family;
    }
  }
}
</style>
